package com.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * GlobalFilter 全局过滤器
 * 用于拦截和处理‌所有经过网关的请求和响应‌，实现跨路由的统一逻辑（如权限验证、日志记录、流量控制等）。它作用于网关的所有路由
 * Ordered 执行顺序控制
 * 当存在多个请求过滤器时，通过getOrder()方法返回值‌确定过滤器的执行优先级‌。值越小优先级越高（支持负数）
 */

@Component
public class JWTAuthFilter implements GlobalFilter, Ordered {

    /**
     * 这里的返回值决定拦截器的优先级，数字越小越先被触发，支持负数
     */
    @Override
    public int getOrder() {
        return -1;
    }

    /**
     * 全局过滤器实现方法
     * @param exchange 获取请求/响应上下文（如请求头、参数等）
     * @param chain chain.filter(exchange)将请求传递给下一个过滤器
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String url = exchange.getRequest().getURI().getPath();
        System.out.println(url);
/*        //跳过不需要验证的路径
        if(url.equals("/admin/auth/login")){
            // 传递给下一级别的过滤器(放行)
            return chain.filter(exchange);
        }
        //跳过不需要验证的路径
        if(url.equals("/admin/auth/logout")){
            // 传递给下一级别的过滤器(放行)
            return chain.filter(exchange);
        }
        //从请求头中取得token
        String token = exchange.getRequest().getHeaders().getFirst("x-token");
        if (StringUtils.isEmpty(token)) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            Response res = new Response(401, "请求头无token");
            byte[] responseByte = JSONObject.fromObject(res).toString().getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(responseByte);
            return response.writeWith(Flux.just(buffer));
        }
        //请求中的token是否有效
        boolean verifyResult = JWTUtil.verify(token);
        if (!verifyResult) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.PAYMENT_REQUIRED);
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            Response res = new Response(402, "token过期");
            byte[] responseByte = JSONObject.fromObject(res).toString().getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(responseByte);
            return response.writeWith(Flux.just(buffer));
        }*/
        // 传递给下一级别的过滤器(放行)
        return chain.filter(exchange);
    }

}
